package com.louis.iread.utils;

import android.content.Context;
import android.os.AsyncTask;
import android.text.BoringLayout;

import com.louis.iread.R;
import com.yarolegovich.lovelydialog.LovelyProgressDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by louis on 17-4-16.
 */

public abstract class SimpleTask extends AsyncTask<String, Integer, Integer> {
    public abstract void doOnPreExe();

    public abstract void doOnPublish(Object ojb);

    public abstract Integer doOnBackgroundExe();

    public abstract void doOnComplete(Integer result);

    protected boolean userWaitingDialog;   //是否需要等待框
    protected LovelyProgressDialog dialog;
    protected Context context;

    public SimpleTask(Context context, boolean userWaitingDialog) {
        this.userWaitingDialog = userWaitingDialog;
        if (this.userWaitingDialog) {
            dialog = new LovelyProgressDialog(context);
            dialog.setIcon(R.drawable.ic_cast_connected_white_36dp)
                    .setTitle(R.string.obtain_data)
                    .setCancelable(true);
        }
    }


    private List<Object> publishList = new ArrayList<>();

    public void publishData(Object obj) {
        if (obj == null) {
            return;
        }
        int size = publishList.size();
        publishList.add(obj);
        publishProgress(size);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (userWaitingDialog) {
            dialog.show();
        }
        doOnPreExe();
    }

    @Override
    protected Integer doInBackground(String... strings) {
        return doOnBackgroundExe();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Object obj = publishList.get(values[0]);
        doOnPublish(obj);
    }

    @Override
    protected void onPostExecute(Integer result) {
        doOnComplete(result);
        if (userWaitingDialog) {
            dialog.dismiss();
        }
    }

}
